
#include "include.h"


nsresult readCodeFile(nsCString file, nsCString &str) {
	FILE* pFile = fopen(file.get(), "rb");
	if (!pFile)
		return NS_ERROR_FAILURE;

	char szBuf[512];
	while (true) {
		size_t r = fread(szBuf, 1, 512, pFile);
		str.Append(szBuf, r);

		if (r < 512) {
			break;
		}
	}
	fclose(pFile);

	return NS_OK;
}

nsresult getAppPath(nsCString &path) {

	nsresult rv;

	nsCOMPtr<nsIServiceManager> serviceManager;
	nsCOMPtr<nsIProperties> properties;


	rv = NS_GetServiceManager(getter_AddRefs(serviceManager));
	if (NS_FAILED(rv)) {
		return rv;
	}

	rv = serviceManager->GetServiceByContractID("@mozilla.org/file/directory_service;1",
		NS_GET_IID(nsIProperties), getter_AddRefs(properties));
	if (NS_FAILED(rv)) {
		return rv;
	}

	nsCOMPtr<nsIFile> nsFile;
	properties->Get(NS_OS_CURRENT_PROCESS_DIR, NS_GET_IID(nsIFile), getter_AddRefs(nsFile));

	nsString str;
	rv = nsFile->GetPath(str);
	if (NS_FAILED(rv)) {
		return rv;
	}
	path = NS_ConvertUTF16toUTF8_external(str.get());

	return rv;
}


PyObject* PRUnicharToPyObject(const PRUnichar *str)
{
	nsAutoString temp(str);
	auto len = temp.Length();
	int order = -1;
	return PyUnicode_DecodeUTF16((const char*)temp.get(), len*sizeof(PRUnichar), NULL, &order);
}

void PyObjectToPRUnichar(const PyObject *str, nsAString &result)
{
	Py_UNICODE *pUnicode = PyUnicode_AsUnicode((PyObject*)str);
	Py_ssize_t size = PyUnicode_GetSize((PyObject*)str);

	PyObject* pz = PyUnicode_EncodeUTF16(pUnicode, size, NULL, -1);
	if (!pz) {
		return;
	}

	PRUnichar* pcc = (PRUnichar*)PyString_AsString(pz);

	PRSize allocSize = (size + 1) * sizeof(PRUnichar);
	PRUnichar* pBuf = (PRUnichar*)NS_Alloc(allocSize);
	memset(pBuf, 0, allocSize);
	memcpy(pBuf, pcc, size * sizeof(PRUnichar));
	NS_Free(pBuf);

	result.Assign(pBuf);
}
